package com.atguigu.juc.one.work;


class Data {
    //初始化数据
    int num = 0;

    //实现一个线程对变量进行+1
    public synchronized  void add(){
        //判断
        if(num !=0){
            try {
                System.out.println(Thread.currentThread().getName()+"等待");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return;
        }
        //干活
        num++;
        System.out.println(Thread.currentThread().getName()+"干活 ，num" + num);
        //通知
        this.notifyAll();
    }

    //实现一个线程对变量进行-1
    public  synchronized  void delete(){
        if(num !=1){
            try {
                System.out.println(Thread.currentThread().getName()+"等待");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return;
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"干活,num"+ num);
        this.notifyAll();
    }

}

//进程通信
//notify 唤醒
//wait  等待
public class NotifyWaitDemo {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {

                data.add();
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {

                data.delete();
            }
        },"BB").start();
    }
}
